package wedaex.helper;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.Header;
import org.apache.commons.lang.StringUtils;

import wedaex.WedaexConfig;
import wedaex.content.Page;

public class HtmlProcessor {
	private static Pattern encodingPattern = Pattern.compile("charset=(.+)( |$)",
			Pattern.CASE_INSENSITIVE|Pattern.DOTALL);
	private static Pattern headStartPattern = Pattern.compile("<head>",
			Pattern.CASE_INSENSITIVE|Pattern.DOTALL);
	private static String URL_SCRIPT = "<script language=\"javascript\">\n" +
			"var wdxProxyUrl = \"URL\";\n" +
			"</script>\n";
	private static int RE_LENGTH = 20;

	public static String getEncoding(Header[] headers) {
		String value = getHeader("Content-Type", headers);
		if(value==null) return "UTF-8";
		Matcher m = encodingPattern.matcher(value);
		if(!m.find()) return "UTF-8";
		String encoding = m.group(1);
		return encoding;
	}
	
	public static String addJavascript(String content) {
		Matcher m = headStartPattern.matcher(content);
		if(!m.find()) return null;
		content = m.replaceFirst("<head>" + WedaexConfig.SCRIPTS);
		return content;
	}

	public static String addProxyInfo(String content, String url) {
		Matcher m = headStartPattern.matcher(content);
		if(!m.find()) return null;
		content = m.replaceFirst("<head>" + URL_SCRIPT.replace("URL", url));
		return content;
	}
	
	private static String getHeader(String headerName, Header[] headers) {
		String value = null;
		for (Header header : headers) {
			if(headerName.equalsIgnoreCase(header.getName())) {
				value = header.getValue();
				return value;
			}
		}
		return null;
	}

	/**
	 * Implements a very simple way of extracting the regular expression
	 * for extracting data from HTML.
	 * @param p			the html page
	 * @param element	user's selected elemnt
	 * @param data		the data user would like to extract
	 * @return			a regular expression that will match data from HTML
	 */
	public static String extractRegularExpression(Page p, String element, String data) {
		String content = p.getContent();
		int elementIndex = content.indexOf(element);
		// TODO elementIndex may be -1 because of various reason.
		// In general, the elementIndex can only help in guessing the user's selection.
		// There is no guarantee that the guess is correct.
		// Need to think of a way to resolve the ambiguity
		
		int textIndex = content.indexOf(data, elementIndex);
		
		System.out.println("element: " + element);
		System.out.println("elementIndex: " + elementIndex);

		// find string near the search text
		int reFromIndex = Math.max(textIndex-RE_LENGTH, 0);
		int reToIndex = Math.min(textIndex+data.length()+RE_LENGTH, content.length());
		
		// construct the regular expression by replacing the search text with (.+)
		String regularExpression = content.substring(reFromIndex, reToIndex);
		regularExpression = RegExpEscape.escape(regularExpression).replace(data, "(.+)");
		
		// Only take the substring without \n
		String[] splits = StringUtils.split(regularExpression, '\n');
		for (String split : splits) {
			if(split.contains("(.+)")) {
				regularExpression = split;
				break;
			}
		}
		
		System.out.println(regularExpression);
		return regularExpression;
	}
}
